package controller;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
import java.io.IOException;

/**
 * @author zhangyanqi
 * @since 1.0 2017/12/3
 */
public class ChattingRoomDecoder implements Decoder.Text<Message> {

    public ChattingRoomDecoder(){
        System.out.println(this.getClass().getName() + "#construct");
    }

    /**
     * Decode the given String into an object of type T.
     *
     * @param s string to be decoded.
     * @return the decoded message as an object of type T
     */
    public Message decode(String s) throws DecodeException {
        Message message = null;
        System.out.println("decode");
        ObjectMapper mapper = new ObjectMapper();
        try {
            message = mapper.readValue(s, Message.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message;
    }

    /**
     * Answer whether the given String can be decoded into an object of type T.
     *
     * @param s the string being tested for decodability.
     * @return whether this decoder can decoded the supplied string.
     */
    public boolean willDecode(String s) {
        System.out.println("判断是否需要解码");
        return true;
    }

    /**
     * This method is called with the endpoint configuration object of the
     * endpoint this decoder is intended for when
     * it is about to be brought into service.
     *
     * @param config the endpoint configuration object when being brought into
     *               service
     */
    public void init(EndpointConfig config) {
        System.out.println(this.getClass().getName() + "#init");
    }

    /**
     * This method is called when the decoder is about to be removed
     * from service in order that any resources the encoder used may
     * be closed gracefully.
     */
    public void destroy() {
        System.out.println(this.getClass().getName() + "#destroy");
    }
}
